package com.service.purchase;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.dao.purchase.ContractChangeDao;
import com.dao.purchase.OrderChangeDao;
import com.enums.ContractTypeEnum;
import com.model.purchase.ContractChangeModel;
import com.model.purchase.OrderChangeModel;
import com.model.purchase.OrderModel;
import com.model.sys.SysUser;
import com.service.external.oa.GetWFStatusService;
import com.service.external.sap.SapPurchaseService;

import ch.qos.logback.core.joran.util.beans.BeanUtil;

import com.common.model.Global;
import com.common.spring.SpringMvcUtils;

@Service
public class ContractChangeService {
	static final Logger logger = LoggerFactory.getLogger(ContractChangeService.class);

	@Autowired
	ContractChangeDao contractChangeDao;
	@Autowired
	OrderChangeDao orderChangeDao;
	@Autowired
	GetWFStatusService getWFStatusService;
	@Autowired
	SapPurchaseService sapPurchaseService;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		List<ContractChangeModel> list = contractChangeDao.selectList(queryMap);
		int count = contractChangeDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String ctrId) {
		HttpResult httpResult = new HttpResult();
		ContractChangeModel contractChangeModel = contractChangeDao.load(ctrId);
		httpResult.setData(contractChangeModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(ContractChangeModel contractChangeModel) {
		if (contractChangeModel == null) {
			return HttpResult.error("参数不能为空");
		}
		OrderChangeModel orderChangeModel = orderChangeDao.load(contractChangeModel.getOrdId());
		if (orderChangeModel == null) {
			return HttpResult.error("订单不存在！");
		}
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (orderChangeModel.getOrdContractType() != null
				&& orderChangeModel.getOrdContractType().equals(Global.YES + "")) {
			if (getWFStatusService.getWFStatus(orderChangeModel.getOaFlowId() + "", sysUser.getWxid())
					.getCode() != HttpStatus.SUCCESS_CODE) {
				return HttpResult.error("oa流程(" + orderChangeModel.getOaFlowId() + ")未审批结束！");
			}
		}
		HttpResult httpResult = new HttpResult();
		int result = 0;
		contractChangeModel.setOrdContractId(orderChangeModel.getOrdContractId());
		contractChangeModel.setOrdContractName(orderChangeModel.getOrdContractName());
		contractChangeModel.setDeptName(orderChangeModel.getInfName());
		if (!StringUtils.isNotNull(contractChangeModel.getCtrId())) {
			contractChangeModel.setCtrId(UUID.randomUUID().toString());
			result = contractChangeDao.insert(contractChangeModel);
		} else {
			result = contractChangeDao.update(contractChangeModel);
		}

		if (result > 0) {
			httpResult.setMsg(contractChangeModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(contractChangeModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(contractChangeModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 提交
	 *
	 * @param
	 * @return
	 */
	public HttpResult commit(ContractChangeModel contractChangeModel) {
		if (contractChangeModel == null) {
			return HttpResult.error("参数不能为空");
		}
		contractChangeModel.setStatus(Global.YES + "");
		HttpResult httpResult = new HttpResult();
		int result = 0;
		OrderChangeModel orderChangeModel = orderChangeDao.load(contractChangeModel.getOrdId());
		if (orderChangeModel == null) {
			return HttpResult.error("订单不存在！");
		}
		if (contractChangeModel.getStatus().equals(Global.YES + "")) {
			orderChangeModel.setStatus(Global.NUMERICAL_TWO + "");// 将订单状态置为2
			orderChangeDao.update(orderChangeModel);
			if (orderChangeModel.getOrdIsSign() != null && orderChangeModel.getOrdIsSign().equals(Global.NO + "")) {
				OrderModel orderModel = new OrderModel();
				BeanUtils.copyProperties(orderChangeModel, orderModel);
				HttpResult sapHttpResult = sapPurchaseService.changeSapOrderStatus(orderModel);
				if (sapHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
					// 强制手动事务回滚
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					logger.error(sapHttpResult.getMsg());
					return HttpResult.error("sap返回：" + sapHttpResult.getMsg());
				}
			}

		}
		result = contractChangeDao.update(contractChangeModel);
		if (result > 0) {
			httpResult.setMsg(contractChangeModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(contractChangeModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(contractChangeModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String ctrId) {
		if (!StringUtils.isNotNull(ctrId)) {
			return HttpResult.error("参数不能为空");
		}
		ContractChangeModel model = contractChangeDao.load(ctrId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		int result = contractChangeDao.delete(ctrId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 撤回
	 *
	 * @param
	 * @return
	 */
	public HttpResult back(String ctrId) {
		if (!StringUtils.isNotNull(ctrId)) {
			return HttpResult.error("参数不能为空");
		}
		ContractChangeModel model = contractChangeDao.load(ctrId);

		// todo

		HttpResult httpResult = new HttpResult();
		model.setStatus(Global.NO + "");
		int result = contractChangeDao.update(model);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<ContractChangeModel> list = contractChangeDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), ContractChangeModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
